package cz.data.common.utils;

import cz.data.common.core.AuthUser;
import cz.data.common.core.BasicToken;
import cz.data.common.core.DataRole;
import cz.data.common.core.DataUser;
import cz.data.common.exception.DataException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.Base64Utils;

import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class SecurityUtil {

    public static DataUser requireDataUser() {
        return Objects.requireNonNull(getDataUser(), "请求上下文不存在用户信息");
    }

    /**
     * 获取用户
     *
     * @return user
     */
    public static DataUser getDataUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            Object principal = authentication.getCredentials();
            if (principal instanceof DataUser) {
                return (DataUser) principal;
            }
        }
        return null;
    }

    /**
     * 获取用户ID
     *
     * @return id
     */
    public static String getUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            Object principal = authentication.getCredentials();
            if (principal instanceof DataUser) {
                return ((DataUser) principal).getId();
            } else if (principal instanceof AuthUser) {
                return ((AuthUser) principal).getId();
            }
        }
        return "";
    }

    /**
     * 获取用户部门
     *
     * @return id
     */
    public static String getUserDeptId() {
        DataUser user = getDataUser();
        if (user != null){
            return user.getDept();
        }
        return "";
    }

    /**
     * 获取用户名称
     *
     * @return username
     */
    public static String getUserName() {
        DataUser user = getDataUser();
        if (user != null){
            return user.getUsername();
        }
        return "";
    }

    /**
     * 获取用户昵称
     *
     * @return nickname
     */
    public static String getNickname() {
        DataUser user = getDataUser();
        if (user != null){
            return user.getNickname();
        }
        return "";
    }

    /**
     * 获取用户角色
     *
     * @return username
     */
    public static List<String> getUserRoleIds() {
        DataUser user = getDataUser();
        if (user != null){
            return user.getRoles().stream().map(DataRole::getId).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    /**
     * 获取用户
     *
     * @return user
     */
    public static boolean isAdmin() {
        DataUser user = getDataUser();
        if (user != null){
            return user.isAdmin();
        }
        return false;
    }

    public static String createBasicToken(String username, String password) {
        String str = username + ":" + password;
        String basicToken = Base64Utils.encodeToString(str.getBytes(StandardCharsets.UTF_8));
        return  "Basic " + basicToken;
    }

    public static BasicToken converterBasicToken(String authorization) {
        if (StringUtils.startsWith(authorization, "Basic "))
            authorization = authorization.substring(6);
        byte[] tokenBytes = Base64Utils.decodeFromString(authorization);
        String basicValue = new String(tokenBytes);
        String[] basicForm = basicValue.split(":");
        if (basicForm.length != 2)
            throw new DataException("Basic凭证解析错误");
        BasicToken token = new BasicToken();
        token.setUsername(basicForm[0]);
        token.setPassword(basicForm[1]);
        return token;
    }

    public static AuthUser getAuthUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            Object principal = authentication.getCredentials();
            if (principal instanceof AuthUser) {
                return (AuthUser) principal;
            }
        }
        return null;
    }

    public static AuthUser requireAuthUser() {
        return Objects.requireNonNull(getAuthUser(), "请求上下文不存在用户信息");
    }
}
